<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String path = request.getContextPath() ;%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> 
<!DOCTYPE html>
<html lang="zh-CN" >
<head>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增授信信息</title>
<jsp:include page="../../import.jsp" flush="true" />
<style type="text/css">
</style>
</head>
<body class="iframeBody">
 <div class="Wrapper">
   <form id="formCrInfo">
     <div class="fieldset1 tabel_col tabel_col_s clearFix">
        <div class="caption">
			<span class="title">授信基础信息 </span>
		</div>
		<div class="fieldBox col_50">
			<div class="label">融资机构名称</div>
			<div class="field">
               <input name="lgcId" id="lgcId" type="hidden" class="ui-textbox" value="${lgcId}"  >
               <input name="fncInsId" id="fncInsId" type="hidden" class="ui-textbox" value="${fncInsId}"  >
               <input name="fncInsShort" id="fncInsShort" type="hidden" class="ui-textbox" value=""  >
               <input name="fncInsNm" id="fncInsNm" type="text" class="ui-textbox" value="" disabled="disabled" >
            </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">授信编号</div>
			<div class="field">
                <input name="crId" id="crId" type="text" class="ui-textbox" value="" disabled="disabled" >
            </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">授信名称</div>
			<div class="field">
                <input name="crNm" id="crNm" type="text" class="ui-textbox" value="" onblur="cnkiCrNm(this.value)" validate="{required:true, maxlength:100}">
           <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">授信合同号</div>
			<div class="field">
                <input name="crCtrNo" id="crCtrNo" type="text" class="ui-textbox" onblur="cnkiCrCtrNo(this.value)" value="" validate="{required:true, maxlength:100}">
           <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">授信主体</div>
			<div class="field">
               <input name="crSbj" id="crSbj" type="text" class="ui-textbox" value="" validate="{required:true}">
           <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">授信额度</div>
			 <div class="field">
                <input name="crLmtnum" id="crLmtnum" type="text" class="ui-textbox" value="" onchange="numChange(this.value)" validate="{required:true}">
                <input name="crLmt" id="crLmt" type="hidden" class="ui-textbox" value="" >
                <span class="requiredSymbol">*</span>
            </div>
             
		</div>
		<div class="fieldBox col_50">
			<div class="label">是否循环授信</div>
			<div class="field">
               <select name="rvlCr" id="rvlCr" data-value=""  validate="{required:true}">
                  <option value="" selected="selected">请选择</option>
                  <c:forEach items="${rvlcrList }" var="kv">
                     <option value="${kv.key }">${kv.value }</option>
                  </c:forEach>
                </select>
                <span class="requiredSymbol">*</span>
             </div>
             
		</div>
		<div class="fieldBox col_50">
			<div class="label">货币类型</div>
			<div class="field">
               <select name="ccyTp" id="ccyTp" data-value=""  validate="{required:true}">
                  <option value="" selected="selected">请选择</option>
                  <c:forEach items="${ccytpList }" var="kv">
					<option value="${kv.key }">${kv.value }</option>
				  </c:forEach>
               </select>
           <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">授信有效期</div>
			<div class="field">
                <input name="stDt" id="stDt" type="text" class="ui-datepicker" value="" validate="{required:true}"><span >&nbsp;至&nbsp;</span>
                <input name="edDt" id="edDt" type="text" class="ui-datepicker" value="" validate="{required:false}">
            <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">是否参与合同审核</div>
			<div class="field">
               <select  name="isPartIn" id="isPartIn" data-value=""  validate="{required:true}">
                  	<option value="" selected="selected">请选择</option>
                    <option value="1">参与</option>
                     <option value="2">不参与</option>
                </select>
             <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_50">
			<div class="label">是否资管</div>
			<div class="field">
               <select  name="zgFlag" id="zgFlag" data-value=""  validate="{required:true}">
                    <option value="0">否</option>
                     <option value="1">是</option>
                </select>
             <span class="requiredSymbol">*</span>
             </div>
		</div>
		<div class="fieldBox col_100" id="fileModify">
			<div class="label">资料</div>
			<div class="field">
               	<jsp:include page="../../system/sysUlFilesRec/sysUlFileRecList.jsp" flush="true" >
                  	<jsp:param name="pkId" value="${lgcId }"/>
                  	<jsp:param name="tabNm" value="CST_BSC_INFO"/>
                </jsp:include>
           	</div>
		</div>
		<div class="fieldBox col_100">
			<div class="label">交易结构</div>
			<div class="field">
                <jsp:include page="../../system/sysUlFilesRec/sysSysUlFilesRecUpload2.jsp" flush="true" >
                  	<jsp:param name="filePath" value="customer"/>
                </jsp:include>
			</div>
	    </div>
	    <div class="fieldBox col_100" >
			<div class="label" style="overflow:visible;word-break:break-all">出账条件及到账指标要求</div>
			<div class="field" style="width:100%" >
			     <textarea name="scmDsc" id="scmDsc" rows="4" class="l-textarea" onclick="addScmDsc()" validate="{required:true, maxlength:500}" style="width:100%"></textarea>
		    </div>
		</div>
	    <div class="fieldBox col_100">
			<div class="label" >权证资料要求</div>
			<div class="field" style="width:100%" >
			     <textarea name="rmrk" id="rmrk" rows="4" class="l-textarea" onclick="addRmrk()" style="width:100%"></textarea>
		    </div>
		</div>
     </div>
     <div class="fieldset1 tabel_col tabel_col_s clearFix">
        <div class="caption">
			<span class="title">历史授信信息 </span>
		</div>
		 <table class="sq-formTable no-border" id="historyCrTable">
          <thead>
            <tr>
               <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">历史授信名称</th>
               <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">历史授信余额</th>
               <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">币种</th>
               <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">是否包含</th>
               <th class="tbLabel" style="text-align: center;background-color: #e7fef4;"><span>操作 </span>
               <a href="javascript:void(0)"  onclick="addHistoryCrNext()"><font style="color:#6495ED;">（添加）</font></a></th>
            </tr>
            </thead>
            <tbody>
           </tbody>
        </table> 
     </div>
     <div class="fieldset1 tabel_col tabel_col_s clearFix">
        <div class="caption">
			<span class="title">关联资产信息 </span>
		</div>
         <table id="tableAst" class="sq-formTable no-border"> 
            <thead>
                <tr>
                    <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">资产占用种类</th>
                    <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">产品编号</th>
                    <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">产品名称</th>
                    <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">授信额度</th>
                    <th class="tbLabel" style="text-align: center;background-color: #e7fef4;">是否可串</th>
                    <th class="tbLabel" style="text-align: center;background-color: #e7fef4;"><span>操作 </span>
                    <a href="javascript:void(0)"  onclick="addAstNext()"><font style="color:#6495ED;">（添加）</font></a></th>
                 </tr>
             </thead>
           <tbody>
           </tbody>
         </table> 
     </div>
     <div class="btnsBox">
		<span id="cr_bsc_info_add_btn_id"
			class="sq-button sq-button-round" onclick="save();">保存
		</span>
		<span id="cr_bsc_info_close_btn_id"
			class="sq-button sq-button-round" onclick="closeWind();">关闭
		</span>
	 </div>
  </form>
</div>

<script type="text/javascript">
  //标识添加或修改
  var addOrUpdate="";
  //历史授信列表
  var historyList=new Array();
  //修改时与新的crBaseInfoVO对比
  var crBaseInfoVO=new Object();
  //授信中的标识常量
  var crStContant="";
  //历史授信改变之前的值
  var hisCrIdBefore="";
  //出账条件及到账指标要求
  var scmDscOldValue="";
  //权证资料要求
  var rmrkOldValue="";
  
  //授信额度输入完显示
  function numChange(num){
	  var numChanged=moneyChange(num);
	  $("#crLmtnum").val(numChanged); 
	  $("#crLmt").val(num);
  }

//格式化金额
  function moneyChange(value) { 
 		var h = '';
 			if(value&&value!="null"){
 		    h+=fmoney(value, 2);
 			}else{
 			h+="0.00";
 			}
          return h;
 		}
  
  //格式化金额
  function fmoney(s, n)   
 	{   
 	   n = n > 0 && n <= 20 ? n : 2;   
 	   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
 	   var l = s.split(".")[0].split("").reverse(),   
 	   r = s.split(".")[1];   
 	   t = "";   
 	   for(i = 0; i < l.length; i ++ )   
 	   {   
 	      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
 	   }   
 	   return t.split("").reverse().join("") + "." + r;   
 	} 
  
//新增回调
  function closeWind(){
	  if(addOrUpdate=="add"){
		  parent.$(".l-dialog,.l-window-mask").css("display","none"); 
		  parent.grid.reload();
		 }else{
		var selectedTabId = parent.mainApp.parentTab.selectedTabId;
		var lastTab = parent.tabItems[0];
		parent.mainApp.parentTab.reload(lastTab.tabid);
		parent.mainApp.parentTab.removeTabItem(selectedTabId);
		parent.grid.reload();
	 }
	 
  }
  
  $(function() {
	 initCrSbjList();
	 $("#formCrInfo").ligerForm({
	     validate: true
	 });
	  initData();
  });
  
  function initData(){
	  var lgcId=$("#lgcId").val();
	  var fncInsId=$("#fncInsId").val();
	  var data=new Object();
	  data["fncInsId"]=fncInsId;
	  if(StringUtils.isNotEmpty(lgcId)){
		  addOrUpdate="update";
		  var _url = '<%=path%>/rfbase/crbaseinfo/toUpdateInit.do';
		  data["lgcId"]=lgcId;
	  }else{
		  addOrUpdate="add";
		  var _url = '<%=path%>/rfbase/crbaseinfo/toAddInit.do';
		  
	  }
	  AjaxUtils.ajaxPost(_url, data, callback);
	}
  
 //新增回调
  function callback(msg){
	if(msg.success == 1){
		 setData(msg.data);//设置数据
	 }else{
		 UIUtils.alertError(msg.info);
	 }
  }
  
  //设置页面数据
  function setData(data){
	 var astList=new Array();
	 historyList=data["historyListValid"];
	 if(addOrUpdate=="add"){
		 var fncInsNm=data["fncInsNm"]; 
		 var fncInsShort=data["fncInsShort"];
		 $("#fncInsNm").val(fncInsNm);
		 $("#fncInsShort").val(fncInsShort);
		 addHistoryCrNext();
		 addAstNext();
	 }else{
		crBaseInfoVO=data["crBaseInfoVO"];
		crStContant=data["crStContant"];
		scmDscOldValue=crBaseInfoVO.scmDsc;
		rmrkOldValue=crBaseInfoVO.rmrk;
		//隐藏的input无法用form.setData赋值，需要用$("#Id").val()形式赋值
		 $("#lgcId").val(crBaseInfoVO.id);
		 $("#fncInsId").val(crBaseInfoVO.fncInsId);
		 $("#crLmt").val(crBaseInfoVO.crLmt);
		 $("#scmDsc").attr("readonly", true);
		 $("#rmrk").attr("readonly", true);
		 //授信主体赋值
		 var crSbj=crBaseInfoVO.crSbj;
		 var manager=$("#crSbj").ligerComboBox({});
		 manager.selectValue(crSbj);  
		
		var form = new liger.get("formCrInfo");  
		var num=moneyChange(crBaseInfoVO.crLmt);
		form.setData({
			fncInsNm : crBaseInfoVO.fncInsNm,
			crId : crBaseInfoVO.crId,
			crNm : crBaseInfoVO.crNm,
			crCtrNo : crBaseInfoVO.crCtrNo,
			crLmtnum :num ,
			rvlCr : crBaseInfoVO.rvlCr,
			ccyTp : crBaseInfoVO.ccyTp,
			stDt : renderDateChange(crBaseInfoVO.stDt),
			edDt :renderDateChange(crBaseInfoVO.edDt),
			rmrk : crBaseInfoVO.rmrk,
			scmDsc : crBaseInfoVO.scmDsc,
			zgFlag : crBaseInfoVO.zgFlag,
			isPartIn:crBaseInfoVO.isPartIn
		});
		
		printHisCrInfo(historyList);
		printAstInfo(crBaseInfoVO.crAstRltvInfoListVO)
	 }
 };
 
 //添加历史授信表
 function printHisCrInfo(displayList)
 {
	var j=0;
	for (var i = 0; i < displayList.length; i++) {
		if(displayList[i].incCrId==null||displayList[i].incCrId=='')
			continue;
		addHistoryCrNext();
		var historyTr = $('#historyCrTable tbody tr:eq('+j+')');
		historyTr.find("select[name='crId']").find("option[value='"+displayList[i].crId+"']").attr("selected",true);
		historyTr.find("input[name='crBal']").val(displayList[i].crBal);
		historyTr.find("input[name='ccyTpNm']").val(displayList[i].ccyTpNm);
		historyTr.find("select[name='isInc']").val(displayList[i].isInc);
		j++;
	}
 }
 
 //选择历史授信时，添加相关资产信息
 function printHisAstInfo(astList)
 {
	var astTrH = $('#tableAst tbody tr');
	var astlength=astTrH.length;
	for (var i = 0; i < astList.length; i++) {
		addHisAstNext();
		var astTr = $('#tableAst tbody tr:eq('+(i+astlength)+')');
		astTr.find("select[name='astId']").val(astList[i].astId);
		astTr.find("input[name='pdId']").val(astList[i].pdId);
		astTr.find("input[name='pdNm']").val(astList[i].pdNm);
		astTr.find("input[name='useLmt']").val(astList[i].useLmt);
		astTr.find("select[name='wthrConn']").val(astList[i].wthrConn);
		astTr.find("input[name='hcrId']").val(astList[i].crId);
		astTr.find("input[name='hid']").val(astList[i].hid);
		astTr.find("input[name='useBal']").val(astList[i].useBal);
		astTr.find("select[name='astId']").attr("disabled",true);
		astTr.find("input[name='pdId']").attr("disabled",true);
		astTr.find("input[name='pdNm']").attr("disabled",true);
	}
 }
 
  //添加该授信的资产信息
 function printAstInfo(astList)
 {
	var astTrH = $('#tableAst tbody tr');
	var astlength=astTrH.length;
	for (var i = 0; i < astList.length; i++) {
		
		if(astList[i].hcrId!=astList[i].crId){
			addHisAstNext();
		}else{
			addAstNext();
		}
		var astTr = $('#tableAst tbody tr:eq('+(i+astlength)+')');
		astTr.find("select[name='astId']").val(astList[i].astId);
		astTr.find("input[name='pdId']").val(astList[i].pdId);
		astTr.find("input[name='pdNm']").val(astList[i].pdNm);
		astTr.find("input[name='useLmt']").val(astList[i].useLmt);
		astTr.find("select[name='wthrConn']").val(astList[i].wthrConn);
		if(astList[i].hcrId!=astList[i].crId){
			astTr.find("input[name='hid']").val(astList[i].hid);
			astTr.find("input[name='hcrId']").val(astList[i].hcrId);
			astTr.find("input[name='useBal']").val(astList[i].useBal);
			astTr.find("select[name='astId']").attr("disabled",true);
			astTr.find("input[name='pdId']").attr("disabled",true);
			astTr.find("input[name='pdNm']").attr("disabled",true);
		}
	}
 }
 
 function f_getDetailData(listChange)
 {
     var data = { Rows: [] };
     for (var i = 0; i < listChange.length; i++)
     {
        data.Rows.push(listChange[i]);
     }
     return data;
 }
 
 function initCrSbjList(){
 	   $("#crSbj").ligerComboBox({
           columns: [
		            { header: '授信主体编号', name: 'key', width: 50}, 
	                { header: '授信主体名称', name: 'value', width: 100}
	               ],
             	url:'<%=path%>/rfbase/crbaseinfo/getCrsbjList.do', 
	            ajaxType :'GET',
	            width: 200,
	            slide: false,
	            selectBoxWidth: 680, 
	            selectBoxHeight: 240,
	            valueField: 'key', 
	            textField: 'value',
	            isMultiSelect: true
	       });
    }
 
      //CSS样式
     var ltextfield ='position: absolute;'
    				   +' top: 0px;'
    				   +' left: 0px;'
    				   +' height: 18px;'
    				   +' line-height: 18px;'
    				   +' padding-left: 0px;'
    				   +' padding-top: 0px;'
    				   +' padding-bottom: 0px;'
    				   +' vertical-align: middle;'
    				   +' background-color: #fff;'
    				   +' width: 174px;'
    				   +' border: 0;'
    				   +' margin: 0;'
    				   +' outline: none;'
    				   +' color: #555555;'
    				   +' border-radius: 4px;';
    	
    	var ltext ='position: relative;'
    				   +' border: 1px solid #e9e9e9;'
    				   +' height: 18px;'
    				   +' line-height: 18px;'
    				   +' width: 178px;'
    				   +' border-radius: 4px;';
    				   

    	var field ='display: inline-block;'
    				   +'vertical-align: top;'
    				   +' height: 18px;'
    				   +' border-spacing: 0;'
    				   +' width: 178px;'
    				   +' border-collapse: collapse;';
    				   
  //添加历史授信行  				   
  function addHistoryCrNext() {
     //设置添加行的内容
        var rowinnerHTML ='<td style="text-align: center;" >'
                    +'<div style="'+ field +'">'
                    +'<select name="crId" style="'+  ltextfield +ltext +'"  onfocus="beforeChangeHisValue(this)"  onchange= "changeHisValue(this)">'
                    +'<option value="">请选择</option>';
                  
          for(var i=0;i<historyList.length;i++){
	        		 rowinnerHTML += '<option value="'+historyList[i].crId +'">'+historyList[i].crNm+'</option>';
	          }        
          
          rowinnerHTML +='</select>'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="crBal" type="text" style="'+ ltextfield +ltext +'"  disabled="disabled" value="" >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="ccyTpNm" type="text" style="'+ ltextfield +ltext +'"  disabled="disabled" value="" >' 
				    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<select name="isInc" style="'+ ltextfield +ltext+'"  data-value="">'
                    +'<option value=" " selected="selected">请选择</option>'
                    +'<option value="0">不包含</option>'
                    +'<option value="1">包含</option>'
                    +'</select>'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +' <a href="javascript:void(0)" onclick="delHistoryCrIndex(this)" style="color:#6495ED;">删除</a>'
                    +'</div>'
                    +'</td>';
	 $('#historyCrTable tbody').append('<tr>'+ rowinnerHTML+'</tr>');  
  }		
 
  //添加删除操作
  function delHistoryCrIndex(obj) {
	    var rowIndex = obj.parentNode.parentNode.parentNode.rowIndex;
	    var historyTr= $('#historyCrTable tbody tr:eq('+(rowIndex-1)+')');
		var historyCrId= $.trim(historyTr.find("select[name='crId'] option:selected").val());
		if(historyCrId!=null&&historyCrId!=""){
			changeAstInfoByHisCr(historyCrId);
		}
		var historyCrTable = document.getElementById("historyCrTable");
		historyCrTable.deleteRow(rowIndex);//删除当前行
	 } 
  
  //历史授信change事件
  function changeHisValue(obj){
	  //获取当前行数，获取改变值
	  var rowIndex = obj.parentNode.parentNode.parentNode.rowIndex; 
	  var historyTr= $('#historyCrTable tbody tr:eq('+(rowIndex-1)+')');
	  var historyCrId= $.trim(historyTr.find("select[name='crId'] option:selected").val());
	  //判断是否存在重复
	  var historyTable = $('#historyCrTable tbody tr');
	  var num=0;
	  for (var i = 0; i < historyTable.length; i++) {
		 var crId = $.trim($(historyTable[i]).find("select[name='crId'] option:selected").val());
		 if(crId==historyCrId){
			 num++;
		 }
	  }
	 if(num>1){
		UIUtils.alertError("选择存在重复，请重新添加！"); 
		var historyCrTable = document.getElementById("historyCrTable");
		historyCrTable.deleteRow(rowIndex);//删除当前行
		return false;
	 }
	 
	  //添加行改变带来的值
	  var rvlCr=null;
	  for(var i=0;i<historyList.length;i++){
		  if(historyList[i].crId==historyCrId){
			  historyTr.find("input[name='crBal']").val(historyList[i].crBal);
			  historyTr.find("input[name='ccyTpNm']").val(historyList[i].ccyTpNm);
			  rvlCr=historyList[i].rvlCr;
			  break;
		  }
	  }
	  //删除改变前历史授信的产品值，添加新历史授信的产品值
	  if(historyCrId!=hisCrIdBefore){
		  if(hisCrIdBefore!=null&&hisCrIdBefore!=''){
			  changeAstInfoByHisCr(hisCrIdBefore);
		  }
		  if(historyCrId!=null&&historyCrId!=''){
		    getHisAstInfo(historyCrId,rvlCr); 
		  }
	  }
  } 
  
  //获取改变后历史授信的产品值
  function getHisAstInfo(crId,rvlCr){
	  var data=new Object();
	  data["crId"]=crId;
	  data["rvlCr"]=rvlCr;
	  var url='<%=path%>/rfbase/crbaseinfo/getAstInfoByCrId.do';
	  $.ajax({
			type: 'post',
			dataType:'json', 
			data:data,
			url: url,
			beforeSend: function(){
		          wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
		     },
			success:function(msg){
				 wait_dialog.close();
				 var e=msg.success;
				 if(msg.success == 1){
					printHisAstInfo(msg.data)
				 }else{
					 $.ligerDialog.error(msg.info);
				 }
			}
		});
  } 
  
  //获取授信改变以前的值
  function beforeChangeHisValue(obj){
	var rowIndex = obj.parentNode.parentNode.parentNode.rowIndex; 
	  var historyTr= $('#historyCrTable tbody tr:eq('+(rowIndex-1)+')');
	  hisCrIdBefore= $.trim(historyTr.find("select[name='crId'] option:selected").val());
  } 
  
  
  //删除改变前授信的资产信息
  function changeAstInfoByHisCr(hisCrIdBefore){
	var astTr = $('#tableAst tbody tr');
	var tableAst = document.getElementById("tableAst");
	for (var i = astTr.length; i > 0; i--) {
		var hcrId = $.trim($(astTr[i-1]).find("input[name='hcrId']").val());
		if(hisCrIdBefore==hcrId){
			tableAst.deleteRow(i);//删除行
		}
	}
  } 
  
  
  //资产关联表相关操作
 function addAstNext() {
   //设置添加行的内容
   var  rowinnerHTML ='<td style="text-align: center;" >'
                    +'<div style="'+ field +'">'
                    +'<select name="astId" style="'+  ltextfield +ltext +'"  data-value="">'
                    +'<option value="" selected="selected">请选择</option>'
                    +'<c:forEach items="${astidList }" var="kv">'
				    +'<option value="${kv.key }">${kv.value }</option>'
			        +'</c:forEach>'
                    +'</select>'
                    +'<input name="useBal" type="hidden" style="'+ ltextfield +ltext +'" value=""  >'
                    +'<input name="hcrId" type="hidden" style="'+ ltextfield +ltext +'" value=""  >'
                    +'<input name="hid" type="hidden" style="'+ ltextfield +ltext +'" value=""  >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="pdId" type="text" style="'+ ltextfield +ltext +'" value="" >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="pdNm" type="text" style="'+ ltextfield +ltext +'" value="" >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="useLmt" type="text" style="'+ ltextfield +ltext +'" value="">'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<select name="wthrConn" style="'+ ltextfield +ltext+'"  data-value="">'
                    +'<option value="" selected="selected">请选择</option>'
                    +'<option value="0">不可串</option>'
                    +'<option value="1">可串</option>'
                    +'</select>'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +' <a href="javascript:void(0)" onclick="delIndex(this)" style="color:#6495ED;">删除</a>'
                    +'</div>'
                    +'</td>';
        $('#tableAst tbody').append('<tr>'+ rowinnerHTML+'</tr>');       
     }   
  
//资产关联表相关操作
 function addHisAstNext() {
   //设置添加行的内容
   var  rowinnerHTML ='<td style="text-align: center;" >'
                    +'<div style="'+ field +'">'
                    +'<select name="astId" style="'+  ltextfield +ltext +'"  data-value="">'
                    +'<option value="" selected="selected">请选择</option>'
                    +'<c:forEach items="${astidList }" var="kv">'
				    +'<option value="${kv.key }">${kv.value }</option>'
			        +'</c:forEach>'
                    +'</select>'
                    +'<input name="hid" type="hidden" style="'+ ltextfield +ltext +'" value=""  >'
                    +'<input name="hcrId" type="hidden" style="'+ ltextfield +ltext +'" value=""  >'
                    +'<input name="useBal" type="hidden" style="'+ ltextfield +ltext +'" value=""  >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="pdId" type="text" style="'+ ltextfield +ltext +'" value="" >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="pdNm" type="text" style="'+ ltextfield +ltext +'" value="" >'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<input name="useLmt" type="text" style="'+ ltextfield +ltext +'" value="">'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'<select name="wthrConn" style="'+ ltextfield +ltext+'"  data-value="">'
                    +'<option value="" selected="selected">请选择</option>'
                    +'<option value="0">不可串</option>'
                    +'<option value="1">可串</option>'
                    +'</select>'
                    +'</div>'
                    +'</td>'
                    +'<td style="text-align: center;">'
                    +'<div style="'+ field +'">'
                    +'</div>'
                    +'</td>';
        $('#tableAst tbody').append('<tr>'+ rowinnerHTML+'</tr>');       
     }   
 //添加删除操作
 function delIndex(obj) {
    var rowIndex = obj.parentNode.parentNode.parentNode.rowIndex;
    var tableAst = document.getElementById("tableAst");
    tableAst.deleteRow(rowIndex);//删除当前行
 } 

 //格式化时间
 function renderDateChange(value){
	var dateStr = "";
	if(null != value &&  ""!= value){
		var date = new Date(value);
		dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
	}
	return dateStr;
 } 
 
 function  cnkiCrNm(crNmNC){
	 var crNm=crNmNC.trim();
	 if(!crNm)return;
	 var url='<%=path%>/rfbase/crbaseinfo/getCnkiCrNm.do?crNm='+crNm;
	 $.ajax({
			type: 'GET',
			dataType:'json', 
			url: url,
			beforeSend: function(){
		          wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
		     },
			success:function(msg){
				 wait_dialog.close();
				 var e=msg.success;
				 if(msg.success == 1){
					if(msg.data==true){
						$.ligerDialog.error("授信名称已存在，请重新填写！");
						$("#crNm").val("");
						document.getElementById("crNm").focus();
					}
				 }else{
					 $.ligerDialog.error(msg.info);
				 }
			}
		});
 }
 
 function  cnkiCrCtrNo(crCtrNoNC){
	 var crCtrNo=crCtrNoNC.trim();
	 if(!crCtrNo)return;
	 var url='<%=path%>/rfbase/crbaseinfo/getCnkiCrCtrNo.do?crCtrNo='+crCtrNo;
	 $.ajax({
			type: 'GET',
			dataType:'json', 
			url: url,
			beforeSend: function(){
		          wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
		     },
			success:function(msg){
				 wait_dialog.close();
				 var e=msg.success;
				 if(msg.success == 1){
					if(msg.data==true){
					   $.ligerDialog.error("授信合同号已存在，请重新填写！");
					   $("#crCtrNo").val(""); 
					   document.getElementById("crCtrNo").focus();
					}
				 }else{
					 $.ligerDialog.error(msg.info);
				 }
			}
		});
 }
 
 //追加出账条件及到账指标要求信息
 function addScmDsc(){
	 if(addOrUpdate=="update"){
		 var innerHtml='<div class="fieldBox col_100" >'
				+'<div class="label" style="color:#6495ED;">出账条件及到账指标要求:</div>'
				+'<div class="field" style="width:100%" >'
				+'<textarea name="scmDscOld" id="scmDscOld"  class="l-textarea" disabled="disabled" validate="{required:true, maxlength:500}" style="width:100%;height:auto;"></textarea>'
				+'</div>'
				+'<br/>'
				+'<div class="field" style="width:100%" >'
				+'<div class="label" style="color:#6495ED;">追加信息:</div>'
				+'<textarea name="scmDscAp" id="scmDscAp" class="l-textarea"  validate="{required:true, maxlength:500}" style="width:100%;height:180px;"></textarea>'
				+'</div>'
				+'</div>';
			 var detailWin= $.ligerDialog.open({
				 target: innerHtml,
		         width: 595, height: 500, top: 80, title: "追加出账条件及到账指标要求信息",allowClose:false,
		         buttons: [
		         {  text: "确定", type: 'ok', cls: 'l-dialog-btn-ok', onclick: function (item, Dialog) {
		        	 var newscmDsc="";
		        	 if($('#scmDscOld').val().trim()!="" ||$('#scmDscOld').val().trim()!=null ){
		        		 newscmDsc=$('#scmDscOld').val().trim()+'\n'+$('#scmDscAp').val().trim();
		        	 }else{
		        		 newscmDsc=$('#scmDscAp').val().trim();
		        	 }
		        	 var form = new liger.get("formCrInfo");  
		     		 form.setData({
		     			scmDsc : newscmDsc
		     		});
		     		detailWin.close();
		         } },
		         {
		             text: "取消", type: 'cancel', cls: 'l-dialog-btn-no',
		             onclick: function (item, Dialog) {
		                 detailWin.close();
		             }
		         }
		         ]
		     });
			document.getElementById("scmDscOld").innerHTML=scmDscOldValue;
	 }
 }

 //追加权证资料要求信息
 function addRmrk(){
	 if(addOrUpdate=="update"){
		 var innerHtml='<div class="fieldBox col_100" >'
				+'<div class="label" style="color:#6495ED;">权证资料要求:</div>'
				+'<div class="field" style="width:100%" >'
				+'<textarea name="rmrkOld" id="rmrkOld"  class="l-textarea" disabled="disabled" validate="{required:true, maxlength:500}" style="width:100%;height:auto;"></textarea>'
				+'</div>'
				+'<br/>'
				+'<div class="field" style="width:100%" >'
				+'<div class="label" style="color:#6495ED;">追加信息:</div>'
				+'<textarea name="rmrkAp" id="rmrkAp" class="l-textarea"  validate="{required:true, maxlength:500}" style="width:100%;height:180px;"></textarea>'
				+'</div>'
				+'</div>';
			 var rmrkWin= $.ligerDialog.open({
				 target: innerHtml,
		         width: 595, height: 500, top: 80, title: "追加权证资料要求信息",allowClose:false,
		         buttons: [
		         {  text: "确定", type: 'ok', cls: 'l-dialog-btn-ok', onclick: function (item, Dialog) {
		        	 var newRmrk="";
		        	 if($('#rmrkOld').val().trim()!="" ||$('#rmrkOld').val().trim()!=null ){
		        		 newRmrk=$('#rmrkOld').val().trim()+'\n'+$('#rmrkAp').val().trim();
		        	 }else{
		        		 newRmrk=$('#rmrkAp').val().trim();
		        	 }
		        	 var form = new liger.get("formCrInfo");  
		     		 form.setData({
		     			rmrk : newRmrk
		     		});
		     		rmrkWin.close();
		         } },
		         {
		             text: "取消", type: 'cancel', cls: 'l-dialog-btn-no',
		             onclick: function (item, Dialog) {
		            	 rmrkWin.close();
		             }
		         }
		         ]
		     });
			document.getElementById("rmrkOld").innerHTML=rmrkOldValue;
	 }
  }
 
 //保存事件
 function save(){
  var ligerForm = liger.get("formCrInfo");
	//是否参与合同审核为必填项 是否参与合同审核
   if($('#isPartIn').val().length==0){
	   UIUtils.alertError("“是否参与合同审核”未选择！");
	   return false;   
   } 
  if (!ligerForm.valid()) {
       top.$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO,SQ_type: "warning"});
       return false; //验证不通过，不执行以下代码
   }
   
   var form = new liger.get("formCrInfo");
   var data = form.getData();
   //隐藏的Input的value用form.getData()无法取到，用Id获取
   data["fncInsId"]=$("#fncInsId").val(); 
   data["fncInsShort"]=$("#fncInsShort").val();
   data["lgcId"]=$("#lgcId").val();
   data["crId"]=$("#crId").val();
   data["crLmt"]=$("#crLmt").val();
   data["crSt"]=crBaseInfoVO.crSt;
   //授信主题值
   var manager=$("#crSbj").ligerComboBox({});
	var crSbj=manager.getValue();  
  
   //比较时间大小
   var timeMin= $("#stDt").val();
   var timeMax= $("#edDt").val();
   var d1 = new Date(timeMin.replace(/\-/g, "\/"));  
   var d2 = new Date(timeMax.replace(/\-/g, "\/"));  
   if(timeMin!=""&&timeMax!=""&&d1 >=d2)  
   {  
	 UIUtils.alertError("“授信有效期”的“开始时间”不能大于“结束时间”！");  
	 return false;  
   }
   
   //资产关联表的数据
   var connMax=0;//所有可串产品的授信额度最大值
   var sumAst=0; //授信额度之和
   
	var astArray = new Array();
	var astTr = $('#tableAst tbody tr');
	for (var i = 0; i < astTr.length; i++) {
		var astId = $.trim($(astTr[i]).find("select[name='astId'] option:selected").val());
		var pdId = $.trim($(astTr[i]).find("input[name='pdId']").val());
		var hid = $.trim($(astTr[i]).find("input[name='hid']").val());
		var pdNm = $.trim($(astTr[i]).find("input[name='pdNm']").val());
		var useLmtold = $.trim($(astTr[i]).find("input[name='useLmt']").val()); 
		var useLmt=useLmtold.replace(",","");
		var useBal = $.trim($(astTr[i]).find("input[name='useBal']").val()); 
		var hcrId = $.trim($(astTr[i]).find("input[name='hcrId']").val()); 
		var wthrConn = $.trim($(astTr[i]).find("select[name='wthrConn'] option:selected").val());
		
		if(astId == null || astId == ''){
			//continue;
			UIUtils.alertError("请选择有效“资产占用种类”！");
			return false;
		}
		if(pdId == null || pdId == ''||pdNm.length>100){
			UIUtils.alertError("请填写100位以下有效“产品编号”");
			return false;
		}
		if(pdNm == null || pdNm == ''||pdNm.length>100){
			UIUtils.alertError("请填写100位以下有效“产品名称”");
			return false;
		}
		if(hid!=null&&hid!=''){
			if(useLmt<useBal){
				UIUtils.alertError("“产品额度”小于编辑前“产品余额”！");
				return false;
			}
		}
		if(useLmt==null||useLmt==''){
			UIUtils.alertError("“资产授信额度”未填写！");
			return false;
		}
		if(/[^0-9\.]/.test(useLmt)||useLmt.length>40){
			UIUtils.alertError("“资产授信额度”,请填写40位以下有效的数字！");
			return false;
		}
		if(wthrConn == null || wthrConn == ''){
			UIUtils.alertError("存在“资产是否可串”未填写");
			return false;
		}
	    if(wthrConn==0){
	   		sumAst +=Number(useLmt);
	   	  }else{
	   		  if(connMax<Number(useLmt)){
	   			connMax=Number(useLmt);
	   		  }
	   	  }
		
		var astInfo = {
			"astId" : astId,
			"pdId" : pdId,
			"pdNm" : pdNm,
			"useLmt" : useLmt,
			"hid" : hid,
			"hcrId" : hcrId,
			"wthrConn" : wthrConn
		}
		astArray.push(astInfo);
	}
	data["astArray"] = JSON.stringify(astArray); 
	
  
	var crLmtSum=$("#crLmt").val();
   //将关联的历史授信表的数据添加data中
	var historyArray = new Array();
	var historyTr = $('#historyCrTable tbody tr');
	for (var i = 0; i < historyTr.length; i++) {
		var crId = $.trim($(historyTr[i]).find("select[name='crId'] option:selected").val());
		var crBal = $.trim($(historyTr[i]).find("input[name='crBal']").val());
		var isInc = $.trim($(historyTr[i]).find("select[name='isInc'] option:selected").val());
		
		if(crId == null || crId == ''){
			continue;
		}
		if(isInc == null || isInc == ''){
			UIUtils.alertError("存在“是否包含”未填写，请检查!");
			return false;
		}
		if(isInc==0){
			crLmtSum +=crBal;
		}
		var historyInfo = {
			"crId" : crId,
			"isInc" : isInc
		}
		historyArray.push(historyInfo);
	}
	data["historyArray"] = JSON.stringify(historyArray);
	
	sumAst +=connMax;//授信额度之和
	if(sumAst>crLmtSum){
		 UIUtils.alertError("授信额度之和不得大于授信总额度，请检查");
		 return false;
	}
	
   //获取附件上传的信息
   var docArray = getUploadResultParams();
   data["docArray"] = JSON.stringify(docArray);
   
   //授信中，保存修改记录
   if(crBaseInfoVO.crSt==Number(crStContant)){ 
	   var udtCnt="";
	   if(renderDateChange(crBaseInfoVO.stDt)!=data["stDt"]||renderDateChange(crBaseInfoVO.edDt)!=data["edDt"]){
		   udtCnt+="授信日期：“"+renderDateChange(crBaseInfoVO.stDt)+"——"+renderDateChange(crBaseInfoVO.edDt)+"”改为“"+data["stDt"]+"——"+data["edDt"]+"” ";
	   }
	   if(crBaseInfoVO.rvlCr!=data["rvlCr"]){
		   var str1="是",str0="否";
		   if(crBaseInfoVO.rvlCr==0){
			  udtCnt+="是否循环授信：“否”改为“是”";
		   }else{
			   udtCnt+="是否循环授信：“是”改为“否”";
		   }
	   }
	   if(crBaseInfoVO.rmrk!=data["rmrk"]){
		   udtCnt+="说明由“"+crBaseInfoVO.rmrk+"”改为“"+data["rmrk"]+"”";
	   }
	   data["udtCnt"]=udtCnt;
   }
   
   var url='<%=path%>/rfbase/crbaseinfo/modify.do';
   if(addOrUpdate=="add"){
	   url='<%=path%>/rfbase/crbaseinfo/add.do'
   }
   //添加
  $.ajax({
		type: 'post',
		dataType:'json', 
		data:data,
		url: url,
		beforeSend: function(){
	          wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
	     },
		success:function(msg){
			 wait_dialog.close();
			 var e=msg.success;
			 if(msg.success == 1){
				 $.ligerDialog.success(msg.info);
				 if(addOrUpdate=="add"){
					 $("#lgcId").val(msg.data);
					 addOrUpdate="update";
					  parent.$(".l-dialog,.l-window-mask").css("display","none"); 
					  parent.grid.reload();
				 }else{
					 var selectedTabId = parent.mainApp.parentTab.selectedTabId;
					 var lastTab = parent.tabItems[0];
					 parent.mainApp.parentTab.reload(lastTab.tabid);
					 parent.mainApp.parentTab.removeTabItem(selectedTabId);
					 parent.grid.reload();
				 }
				
			 }else{
				 $.ligerDialog.error(msg.info);
			 }
		}
	});
}
</script>
</body>
</html>
